<template>
	<view class="content">
		<u-navbar :fixed="false" title="用料清单" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
		</u-navbar>

		<view class="MainBox">
			<!-- 非空数据 -->
			<view class="HasDataBox" v-if="PageList.length">
				<!-- 排序列表 -->
				<!-- <view> -->
				<m-basic-drag class="ListBox" v-model="PageList" itemKey="index" :column="1" itemHeight="160px"
					height="100%">
					<template #item="{element,index}">

						<view class="MaxBox x-f">
							<view class="TheIndex x-f">
								<view class="IndexBox">
									<text>{{index +1}}</text>
								</view>
							</view>

							<view class="x-f" style="flex: 1;height: 100%;padding: 10px 16px 10px 6px;">

								<view class="x-bc"
									style="background-color: #fff;height: 100%;width: 100%;padding: 6px 10px;border-radius: 12px;">
									<view class="LeftBox x-f">
										<u-icon name="minus-circle-fill" color="#f56c6c" size="24"
											@click="DeleteListData(element,index)"></u-icon>

										<view style="padding-left: 8px;color: #999;">
											<view
												style="color: #333;font-size: 14px;font-weight: 600;width: 100%;word-break: break-all;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;margin-bottom: 4px;">
												{{element.ProductCode}} | {{element.ProductName}} |
												{{element.ProductSpec}}
											</view>

											<view style="margin-top: 4px;font-size: 12px;">
												<text>父件基数：</text>
												<text>{{element.ParentNum}}</text>
											</view>
											<view style="margin-top: 4px;font-size: 12px;">
												<text>子件用量：</text>
												<text>{{element.SunNume}}</text>
											</view>
											<view style="margin-top: 4px;font-size: 12px;">
												<text>损耗率：</text>
												<text>{{element.LossRatio}}</text>
											</view>
										</view>
									</view>

									<view class="RightBox x-f" style="height: 100%;">

										<u-icon name="list" color="#999" size="28"
											style="font-weight: 600;margin-right: 6px;"></u-icon>

										<uni-icons type="compose" color="#999" size="28"
											@click="EditCell(element,index)"></uni-icons>
									</view>
								</view>
							</view>
						</view>
					</template>
				</m-basic-drag>
			</view>

			<!-- 空状态 -->
			<view class="isEmptyBox" v-else>
				<u-empty mode="data" icon="/static/image/Img/DataEmpty.png" text="暂无用料" textColor="#999"
					style="margin: 0 auto;">
					<!-- <view class="EmptyTextBox">
						<view class="EmptyText">
							<text>可选择【按BOM添加】或【添加用料】</text>
						</view>
					</view> -->
				</u-empty>
			</view>



			<view class="AddRowBtnBox">
				<view class="BtnBox" style="margin: 20px 0;min-width: 100%;">
					<button @click="OpenPopup('Materials')" class="SaveBtn">
						<uni-icons type="plusempty" color="#51d0d0" size="20"></uni-icons>
						添加用料
					</button>

				</view>
				<!-- <view class="BtnText x-f" @click="OpenPopup('Bom')">
					<uni-icons color="#51d0d0" size="20">{{$utils.toUniCode('&#xe98e;')}}</uni-icons>
					<text class="text">按BOM添加</text>
				</view>

				<view style="width: 40px;text-align: center;color: #999;">|</view>

				<view class="BtnText x-f" @click="OpenPopup('Materials')">
					<uni-icons type="plusempty" color="#51d0d0" size="20"></uni-icons>
					<text class="text">添加用料</text>
				</view> -->
			</view>
		</view>


		<view class="BottomBox" :style="$utils.disposeSafeBottomFun()">

			<button class="SaveBtn CommonBtnSize">更新用料清单</button>
			<button class="SubBtn CommonBtnSize" @click="SubmitBtn">确定</button>
		</view>




	</view>
</template>

<script>
	import MorkData_All from '@/static/MorkData/MorkData_All.js';
	// 工艺路线
	export default {
		data() {
			return {
				ProductID_Main: null, // 外部产品ID
				PageList: [], // 主列表数据
				ShowChoiceBom: false, // 选择BOM弹层
				searchValue: '', // 弹层搜索框
				PopupLoadStatus: 'nomore',
				page: {
					pageIndex: 1, // 页码
					pageSize: 30, // 每页数量
				},

				ShowBomCellInfo: false, // Bom弹层 - cell 详情弹层
				BomList: [], // Bom弹层数据
				Nums: 1,

				ShowChoiceMaterials: false, // 添加用料弹层
				MaterialsList: [], // 添加用料列表数据
				IsCheckedLength: 0, // 已选中数量
				CheckedAll: false,

				ShowMaterialsCellInfo: false, // 用料清单 - 产品详情 弹层
				PopupInfo: { // 数据详情
					ProductCode: '',
					ProductName: '',
					Data: [],
				},
				EditIndex: null, // 选中的主列表索引
			}
		},
		onLoad(option) {
			this.ProductID_Main = option.ProductID;

			let Data = [];
			Data = JSON.parse(JSON.stringify(this.$store.state.TicketModule.CreateTicket_Materials));

			if (Data.length) {
				Data.map((item, index) => {
					item['index'] = index;
				})
				this.PageList = JSON.parse(JSON.stringify(Data))
			}
		},
		watch: {},
		mounted() {
			var that = this;
			// 监听 选择产品
			uni.$on('MaterCellInfo_Config', function(ret) {
				// console.log(ret)
				if (ret.type == '编辑用料') {

					Object.assign(that.PageList[that.EditIndex], ret.data);

					that.PageList = JSON.parse(JSON.stringify(that.PageList));

					that.PageList.map((item, index) => {
						item['index'] = index
					});
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: {}
					})
				} else if (ret.type == '添加用料') {
					let newData = JSON.parse(JSON.stringify(ret.data));
					let isFictional = false;
					// 判断是否为虚设件

					// 定义字段名和默认值的数组
					const fields = [{
							name: 'ParentNum',
							defaultValue: 1
						},
						{
							name: 'SunNume',
							defaultValue: 1
						},
						{
							name: 'LossRatio',
							defaultValue: 0
						}
					];

					let ProductID = [],
						ParentNum = [],
						BomDeID = [],
						LossRatio = [],
						SunNume = [],
						BomID = [];

					// 遍历 newData 数组，对每一项对象进行判断和处理
					newData = newData.map((item, index) => {

						// 对每一个字段进行判断和处理
						fields.forEach(field => {
							if (!(field.name in item) || item[field.name] === null || item[field
									.name] === undefined) {
								// 如果没有字段或字段值为 null/undefined，则增加字段并默认为指定的默认值
								item[field.name] = field.defaultValue;
							} else {
								// 如果有字段且字段有值，则判断字段是否有值，没有值则默认为指定的默认值
								if (item[field.name] === '') {
									item[field.name] = field.defaultValue;
								}
							}
						});

						if (item.hasOwnProperty('Attribute') && item.Attribute == 4) {
							isFictional = true;
							ProductID.push(item.ProductID);
							ParentNum.push(item.ParentNum);
							BomDeID.push(item.BomDeID || 0);
							LossRatio.push(item.LossRatio);
							SunNume.push(item.SunNume);
							BomID.push(item.BomID || 0);
						}
						item['index'] = index
						return item;
					});


					// newData.forEach(item => {
					// 	ProductID.push(item.ProductID);
					// 	ParentNum.push(item.ParentNum);
					// 	BomDeID.push(item.BomDeID || 0);
					// 	LossRatio.push(item.LossRatio);
					// 	SunNume.push(item.SunNume);
					// 	BomID.push(item.BomID || 0);
					// })
					console.log(isFictional);
					if (isFictional) {
						let obj_new = {
							ProductID: ProductID.join('~'),
							ParentNum: ParentNum.join('~'),
							BomDeID: BomDeID.join('~'),
							LossRatio: LossRatio.join('~'),
							SunNume: SunNume.join('~'),
							BomID: BomID.join('~'),
						}
						that.getIsVirtualPieces(obj_new)
					} else {
						that.PageList = JSON.parse(JSON.stringify(newData));
					};
				}
			})

		},
		onUnload() {
			uni.$off('MaterCellInfo_Config')
		},
		methods: {
			/**
			 * 判断选中的物料是否为虚设件
			 * @param {Object} param 参数
			 */
			getIsVirtualPieces(param) { // 判断选中的物料是否为虚设件
				let that = this;
				try {
					let oldData = JSON.parse(JSON.stringify(that.PageList));
					this.Request.request('XGD_SelectMaterial', param, (ret) => {
						if (ret.status == 200) {
							that.PageList = oldData.concat(ret.data.ds);
						}
					}, (err) => {
						console.log(err);
					})
				} catch (e) {
					layer.alert('请求异常，请稍后重试！')
					//TODO handle the exception
				}
			},
			EditCell(data, index) { // 编辑主列表 cell 数据
				this.EditIndex = index;

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: data
				})
				uni.navigateTo({
					url: './MaterialsListCellInfo'
				})
			},
			DeleteListData(data, index) { // 主列表 删除按钮

				this.PageList.splice(index, 1)
			},
			OpenPopup(str) {
				this.PopupLoadStatus = 'loadmore'; // 加载状态初始化
				this.page.pageIndex = 1; // 页数初始化

				if (str == 'Bom') {
					return uni.showToast({
						title: '此通道暂未开启',
						icon: 'none'
					})
					this.BomList = MorkData_All.MaterialsList_BOM();
					this.ShowChoiceBom = true;
				} else if (str == 'Materials') {

					let obj = {
						allowClear: false,
						cmd: 'XGD_Material',
						type: '添加用料',
						ListeningName: 'MaterCellInfo_Config',
						// multiple: false,
						serverSearch: {
							isPaging: true, //是否分页
							searchKey: 'SearchKey', //搜索关键词，应包含在param中
							showText: 'ProductInfo', //查询结果显示的字段
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
							ChoiceDataKey: 'ProductID',
							ChoiceDataData: this.PageList,
							disabledCellID: [this.ProductID_Main], // 需要禁选的ID
							disabledKey: 'ProductID'
						},
						param: {
							SearchKey: '',
							PageIndex: 1,
							PageSize: 30
						}
					}

					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})

					uni.navigateTo({
						url: '/commonPage/Tool/SelectBaseScreen'
					})


					// let data = JSON.parse(JSON.stringify(MorkData_All.MaterialsList_Materials()));
					// data.map(item => {
					// 	item.checked = false;
					// })
					// this.MaterialsList = data;


					// this.MaterialsList = [];
					// this.loadmoreMaterials();
					// this.ShowChoiceMaterials = true;
				}
			},
			closeChoiceBomPopup() { // 关闭选择BOM弹层
				this.ShowChoiceBom = false;
				this.BomList = [];
			},
			closeBomInfoPopup() { // 关闭Bom弹层 - 详情弹层
				this.ShowBomCellInfo = false;
				this.Nums = 1;
			},
			SubBomData() { // 确认按Bom添加数据
				let data = [{
					ProductName: '556asdsas',
					Nums: 1,
					Process: '-',
					id: 0,
				}, {
					ProductName: 'qweqwe12',
					Nums: 1,
					Process: '封边',
					id: 1,
				}];
				this.PageList.push(...data);
				this.PageList.map((item, index) => {
					item.index = index;
				})
				this.closeBomInfoPopup();
				this.closeChoiceBomPopup();
			},
			closeChoiceMaterialsPopup() { // 关闭添加用料弹层
				this.MaterialsList = [];
				this.ShowChoiceMaterials = false;
				this.CheckedAll = false;
			},
			OpenCellInfo(data) { // 添加用料 - 查看
				const resultArray = Object.keys(data).map(key => {
					let getData = this.conversionData(key);

					let obj = {
						AttributeName: key,
						AttributeData: data[key],
					};

					return {
						...obj,
						...getData
					}
				});

				this.PopupInfo.ProductName = data.ProductName;
				this.PopupInfo.ProductCode = data.ProductCode;
				this.PopupInfo['Data'] = resultArray;
				this.ShowMaterialsCellInfo = true;
			},
			ChoiceMaterialsData(data) { // 添加用料 点击cell
				// console.log(JSON.stringify(data))

				data.checked = !data.checked;
				// console.log(JSON.stringify(this.MaterialsList))

				let CheckedNums = this.MaterialsList.filter(item => item.checked).length;

				this.IsCheckedLength = CheckedNums;

				if (CheckedNums == this.MaterialsList.length && this.MaterialsList.length != 0) {
					this.CheckedAll = true;
				} else {
					this.CheckedAll = false;
				}
			},
			ToggleChecked() { // 添加用料 - 切换全选

				this.MaterialsList.forEach(item => {
					item.checked = !this.CheckedAll;
				});

				this.CheckedAll = !this.CheckedAll;

				this.IsCheckedLength = this.MaterialsList.filter(item => item.checked).length;

			},
			SubMaterialsData() { // 确定 用料清单选中
				var that = this;


				let FilterData = this.MaterialsList.filter(item => item.checked);

				let HasID = FilterData.some(item => {
					return item.ProductID == that.ProductID_Main;
				});
				if (HasID) {
					return uni.showToast({
						title: '父项产品与子项产品不能相同',
						icon: 'none'
					})
				}

				let data = FilterData.map(item => {
					return {
						...item,
						ProductName: String(
							`${item.ProductCode} | ${item.ProductName} | ${String(item.ProductSpec)}`),
						Nums: 1,
						Process: '-',
						id: item.ProductID,
					}
				})
				this.PageList.push(...data);
				this.PageList.map((item, index) => {
					item.index = index;
				})
				this.closeChoiceMaterialsPopup();
			},
			closeMaterialsInfoPopup() { // 关闭 用料清单 - 产品详情弹层
				this.ShowMaterialsCellInfo = false;
			},

			scrolltolower(str) { // 列表触底
				if (str == 'BOM') {
					this.loadmore();
				} else if ('Materials') {
					this.loadmoreMaterials();
				}
			},
			loadmoreMaterials() { // 添加用料数据接口
				let that = this;

				if (that.PopupLoadStatus == 'nomore') return;
				that.PopupLoadStatus = 'loading';

				let obj = {
					SearchKey: this.searchValue,
					PageIndex: this.page.pageIndex,
					PageSize: this.page.pageSize,
				};
				that.Request.request('XGD_Product', obj, function(ret) {

					if (ret.status == 200) {
						that.TotalPopup = ret.data.ds1[0]['Total'];

						ret.data.ds.map(item => {
							item.checked = false;
						})

						that.MaterialsList.push(...ret.data.ds);

						that.page.pageIndex++;

						that.PopupLoadStatus = 'loadmore';
						if (that.MaterialsList.length == ret.data.ds1[0]['Total']) {
							that.PopupLoadStatus = 'nomore';
						}
					}
				});
			},
			conversionData(data) { // 转换 用料清单 - 产品详情 数据
				let obj = {
					isShow: false,
					Icons: '',
					Names: '-'
				}
				switch (data) {
					case 'UnitName':
						obj.isShow = true;
						obj.Names = '单位';
						obj.Icons = 'icon-guige'
						break;
					case 'ProductSpec':
						obj.isShow = true;
						obj.Names = '产品规格';
						obj.Icons = 'icon-guige'
						break;
					case 'AttributeName':
						obj.isShow = true;
						obj.Names = '产品属性';
						obj.Icons = 'icon-Icon_shuxing'
						break;
					case 'FWorkshopName':
						obj.isShow = true;
						obj.Names = '工作中心';
						obj.Icons = 'icon-yuanxiaopaiming'
						break;
					case 'SafeStock':
						obj.isShow = true;
						obj.Names = '最低安全库存';
						obj.Icons = 'icon-yuanxiaopaiming'
						break;
					case 'MAXSafeStock':
						obj.isShow = true;
						obj.Names = '最高安全库存';
						obj.Icons = 'icon-yuanxiaopaiming'
						break;
					case 'FQty':
						obj.isShow = true;
						obj.Names = '当前库存数量';
						obj.Icons = 'icon-yuanxiaopaiming'
						break;
					default:
						obj.isShow = false;
						break;
				}

				return obj;
			},
			SubmitBtn() { // 主列表确认按钮
				var that = this;

				function HasData(obj, prop) {
					if (obj.hasOwnProperty(prop) && !that.$utils.isEmpty(obj[prop])) {
						return false;
					} else {
						return true;
					}
				}

				this.PageList.forEach(item => {

					if ('BomID' in item) {} else {
						item['BomID'] = 0;
					}
					if ('BomDeID' in item) {} else {
						item['BomDeID'] = 0;
					}
				})

				this.PageList.map((item, index) => {
					item.index = index
				});

				let Obj = {
					Name1: 'CreateTicket_Materials',
					data: this.PageList
				};

				this.$store.commit('TicketModule/ChangeAndSetStateData', Obj);

				uni.$emit('CreateTicet_Choice', {
					type: '用料清单',
					data: this.PageList
				});

				uni.navigateBack();
			},
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		// height: calc(100vh - 60px);
		background-color: #f9f9f9;

		.MainBox {
			flex: 1;
			overflow: auto;

			.HasDataBox {
				// display: flex;
				// flex-direction: column;

				.ListBox {
					.MaxBox {
						height: 100%;

						.TheIndex {
							height: 100%;
							min-width: 60px;
							justify-content: center;

							.IndexBox {
								width: 24px;
								height: 24px;
								background-color: #51d0d0;
								color: #fff;
								border-radius: 24px;
								line-height: 24px;
								text-align: center;
							}
						}
					}
				}

				.BtnBox {
					display: flex;
					align-items: center;
					justify-content: center;

					.SaveBtn {
						width: 80%;
						color: #51d0d0;
						background-color: #fff;
						border: 1px solid #51d0d0;
						border-radius: 12px;
					}
				}
			}

			// 复选框样式 start
			.uni-checkbox-input {
				border: 2px solid #d1d1d1 !important;
			}

			.uni-checkbox-input-checked {
				background: #51d0d0;
				color: #fff !important;
				border-color: #51d0d0 !important;
			}

			// 复选框样式 End

			.AddRowBtnBox {
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: 600;
				margin-top: 20px;
				padding-bottom: 20px;

				.BtnBox {
					display: flex;
					align-items: center;
					justify-content: center;

					.SaveBtn {
						width: 80%;
						color: #51d0d0;
						background-color: #fff;
						border: 1px solid #51d0d0;
						border-radius: 12px;
					}
				}

				.BtnText {
					width: 40vw;
					padding: 6px 10px;
					text-align: center;
					color: #51d0d0;
					justify-content: flex-end;

					.text {
						color: #51d0d0;
						margin-left: 4px;
					}
				}

				.BtnText:last-child {
					justify-content: flex-start;
				}
			}

			.MaterialsBox {
				background-color: #ebebeb;

				.u-cell {

					.u-cell__body {
						padding: 0 !important;
					}

					.CellRight {
						padding-right: 10px;
					}
				}
			}

			.PopupMainBox {
				height: 90vh;
				display: flex;
				flex-direction: column;

				.SearchBox {
					// background-color: #fff;
					background-color: #51d0d0;
					padding: 6px 10px;
				}

				// .ListItemBox {
				// height: 100%;


				.ListCellLeft {

					.CheckBox {
						padding: 14px 15px;
						width: 100%;

						.TitleBox {
							margin-left: 6px;
							font-size: 16px;
						}

						.CellLabel {
							color: #818181;
							font-size: 14px;
							margin-top: 6px;
							width: calc(100vw - 80px - 100px);
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
						}
					}
				}

				.Popup_Look {
					background-color: #51d0d0;
					color: #fff;
					border-radius: 8px;
					min-width: 30px;
					height: 30px;
					line-height: 30px;
					font-size: 12px;
					margin-right: 10px;
				}

				.PopupBottomBox {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 10px 15px;
					border-top: 1px solid #efefef;
					background-color: #fff;

					.LeftBox {
						display: flex;
						align-items: center;

						.ChoiceNumBox {
							margin-left: 10px;
							width: fit-content;

							.Nums {
								margin: 0 4px;
								color: #51d0d0;
								font-size: 18px;
								font-weight: 600;
							}
						}
					}


					.BtnBox {
						// flex: 1;
						display: flex;
						justify-content: flex-end;
						align-items: center;

						.SubBtn {
							// width: 40%;
							min-width: 200px;
							background-color: #51d0d0;
							color: #fff;
							border-radius: 12px;
						}
					}
				}

				// }
			}
		}

		.BottomBox {
			display: flex;
			justify-content: space-evenly;
			align-items: center;
			padding: 10px 15px;
			background-color: #fff;
			border-top: 1px solid #efefef;

			.SaveBtn {
				width: 44%;
				background-color: #fff;
				color: #51d0d0;
				border: 1px solid #51d0d0;
				border-radius: 12px;
			}

			.SubBtn {
				width: 40%;
				background-color: #51d0d0;
				color: #fff;
				border-radius: 12px;
			}
		}
	}
</style>